package jsj.open.lib.piccrop

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewGroup
import android.widget.FrameLayout

class ImageCropWrapper(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) :
    FrameLayout(context!!, attrs, defStyleAttr) {
    data class CropResult(var viewWidth:Int,var viewHeight:Int,val rect:Rect)
    data class CropResultPercent(val leftPercent:Float,val topPercent:Float,val rightPercent:Float,val bottomPercent:Float)

    constructor(context: Context?):this(context,null,0)
    constructor(context: Context?,attrs: AttributeSet?) : this(context,attrs,0)
    private val imageCrop: ImageCrop
    init{
        imageCrop = ImageCrop(context)
        addView(imageCrop,FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT))
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        super.dispatchTouchEvent(ev)
        imageCrop.onTouchEventSelf(ev!!)
        return true
    }
    fun lock16_9(lock:Boolean){
        imageCrop.lock16_9(lock)
    }

    fun setBitmap(bitmap: Bitmap){
        imageCrop.setImageBitmap(bitmap)
    }
    fun crop(): CropResult {
        return CropResult(imageCrop.measuredWidth,imageCrop.maxHeight,imageCrop.bounds)
    }
    fun cropByPercent(): CropResultPercent {
        var l = 0f
        var t=0f
        var r=0f
        var b=0f
        imageCrop.bounds.apply {
            l = (1f*left/measuredWidth).coerceIn(0f,1f)
            t = (1f*top/measuredHeight).coerceIn(0f,1f)
            r = (1f*right/measuredWidth).coerceIn(0f,1f)
            b = (1f*bottom/measuredHeight).coerceIn(0f,1f)
        }
        return CropResultPercent(l,t,r,b)
    }

}